#复位
#绕框
#黑小框
#任意放黑小框
#绿追红，距离小于三厘米
#绿追红，跟一起走框

import cv2
import numpy as np

Binarization = 131  #二值化参数
canny_min = 0
canny_max = 0
offset = 9
max_area = 20000
min_area = 10000

#二值化回调函数
def call_back_Threshold(Binarization_num):
    global Binarization
    Binarization = Binarization_num

def call_back_Canny_max(Canny_num):
    global canny_max
    canny_max = Canny_num

def call_back_Canny_min(Canny_num):
    global canny_min
    canny_min = Canny_num

def call_back_offset(adapt_offset):
    global offset
    offset = adapt_offset

def call_back_minsize(min):
    global min_area
    min_area = min

def call_back_maxsize(max):
    global max_area
    max_area = max

#提取轮廓
def Extract_the_edges(img):
    global canny_min, canny_max, offset
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    img = cv2.GaussianBlur(img, (5, 5), sigmaX=0.6)             #高斯滤波
    # cv2.imshow("2", img)

    ret, img = cv2.threshold(img, Binarization, 255, cv2.THRESH_BINARY)  #二值化
    cv2.imshow("2zh", img)
    #img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, offset)
    # cv2.imshow("2zh ada", img)

    img = cv2.Canny(img, canny_min, canny_max)                       #canny算子
    cv2.imshow("canny", img)
    return img

def find_rectangle(img):
    global min_area, max_area
    contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    for i in contours:
        area = cv2.contourArea(i)
        #TODO:轮廓近似
        if area > min_area and area < max_area:
            img_new = np.zeros((480, 640, 3), dtype=np.uint8)
            #cv2.imshow("Finall", img_new)
            cv2.drawContours(img_new, i, -1, (255, 255, 255), 5)
            gray = cv2.cvtColor(img_new, cv2.COLOR_BGR2GRAY)
            dst = cv2.cornerHarris(gray, 2, 3, 0.04)
            corner_mask = dst > 0.1 * dst.max()
            corner_positions = np.where(corner_mask)
            #TODO:筛选，使用多一张图片来筛选
            num_i = 0
            for y, x in zip(corner_positions[0], corner_positions[1]):
                cv2.circle(img_new, (x, y), 3, (255, 0, 255), -1)
                num_i = num_i + 1

            print(num_i)
            cv2.imshow("Finall", img_new)

#摄像头初始化
cap = cv2.VideoCapture(0) #设备号为0
#参数框设置
cv2.namedWindow('parameter', cv2.WINDOW_KEEPRATIO)
cv2.createTrackbar('Threshold_0', 'parameter', 0, 255, call_back_Threshold)
# cv2.createTrackbar('canny_max', 'parameter', 0, 255, call_back_Canny_max)
# cv2.createTrackbar('canny_min', 'parameter', 0, 255, call_back_Canny_min)
cv2.createTrackbar('adapt_thr_offset', 'parameter', 0, 255, call_back_offset)
cv2.createTrackbar('min area', 'parameter', 0, 30000, call_back_minsize)
cv2.createTrackbar('max area', 'parameter', 0, 30000, call_back_maxsize)
if cap.isOpened() == False:
    print('can not open camera')
    exit(0)

if __name__ == '__main__':
    while(True):
        ret, frame = cap.read()  # 读取图像
        cv2.imshow("ori", frame)
        frame = Extract_the_edges(frame)
        find_rectangle(frame)
        key = cv2.waitKey(1)
        if key & 0xFF == ord('q'):
            break